package com.tehui.activity.impl;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.tehui.R;
import com.tehui.utils.tools.PrefUtils;
import com.tehui.utils.ui.UiUtils;
import com.tehui.utils.web.MyCallback;
import com.tehui.utils.web.NR;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

import static com.tehui.app.MyApplication.IS_TAOKE;

public class SplashActivity extends Activity {

    @BindView(R.id.time)
    TextView  time;
    @BindView(R.id.splash)
    ImageView splash;
    private boolean          stage;
    private MyCountDownTimer mCDT;
    private String           taokeId;
    private String           imei;

    private boolean permission = true;

    //闪屏页面
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams
                .FLAG_FULLSCREEN);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);

        taokeId = getString(R.string.taokeId);
        imei = UiUtils.getIMEI(this);
        //                if (true) {
        //                    startActivity(new Intent(this, WebActivity.class));
        //                    return;
        //                }
        if (IS_TAOKE) {
            usePermission();
        }
        getServre();

        boolean uploadImei = PrefUtils.getBoolean("uploadImei", false);
        if (!uploadImei) {
            uploadImei();
        }
        //        Intent intent = getIntent();
        //        stage = intent.getBooleanExtra("stage", false);

        mCDT = new MyCountDownTimer(4000, 1000);
        mCDT.start();
    }

    private void uploadImei() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("taokeId", taokeId);
            jsonObject.put("phoneSign", imei);
            String s = jsonObject.toString();
            NR.postRequest("http://dl.21tehui.com/GetPhoneOnlySignApi.html", "key", s, "imei", new
                    MyCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    super.onSuccess(s, call, response);
                    PrefUtils.setBoolean("uploadImei", true);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void getServre() {

        if (UiUtils.isNetworkAvailable()) {
            OkGo.get("http://dl.21tehui.com/AdImgApi.html?type=1").tag(this).cacheKey("cacheKey").cacheMode
                    (CacheMode.DEFAULT).execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    try {
                        JSONArray jsonArray = new JSONArray(s);
                        String o = jsonArray.get(0).toString();
                        JSONObject jsonObject = new JSONObject(o);
                        String image = jsonObject.optString("image", "");
                        String link = jsonObject.optString("link");
                        initSplash(image, link);
                    } catch (JSONException e) {
                    }
                }

                @Override
                public void onError(Call call, Response response, Exception e) {
                }
            });
        } else {
            Glide.with(UiUtils.getContext()).load(R.drawable.splash).into(splash);
        }
    }

    private void initSplash(String image, String link) {
        Glide.with(UiUtils.getContext()).load(image).into(splash);
        splash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //UiUtils.toast("点击了");
            }
        });
    }

    public void initFirstIn() {
        if (UiUtils.isNetworkAvailable()) {
            if (permission) {
                startActivity(new Intent(this, HomeActivity.class));
                finish();
            } else {
                startActivity(new Intent(this, LimitActivity.class));
                finish();
            }
        } else {
            boolean usePermission = PrefUtils.getBoolean("usePermission", true);
            if (usePermission) {
                startActivity(new Intent(this, HomeActivity.class));
                finish();
            } else {
                startActivity(new Intent(this, LimitActivity.class));
                finish();
            }
        }
    }

    @OnClick(R.id.jump)
    public void onClick() {
        mCDT.cancel();
        //        if (stage) {
        //            finish();
        //        } else {
        initFirstIn();
        //        }
    }

    //使用权限
    public void usePermission() {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("TaokeId", taokeId);
            OkGo.post("http://dl.21tehui.com/AppStateApi.html").tag(this).params("TaokeId", jsonObject
                    .toString()).cacheKey("cacheKey").cacheMode(CacheMode.DEFAULT).execute(new StringCallback() {
                @Override
                public void onSuccess(String s, Call call, Response response) {
                    if (s.equals("0")) {
                        PrefUtils.setBoolean("usePermission", true);
                        setPermission(true);
                    } else {
                        PrefUtils.setBoolean("usePermission", false);
                        setPermission(false);
                    }
                }

                @Override
                public void onError(Call call, Response response, Exception e) {
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void setPermission(boolean permission) {
        this.permission = permission;
    }

    class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long l) {
            time.setText(l / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            time.setText("0秒");
            //            if (stage) {
            //                finish();
            //            } else {
            initFirstIn();
            //            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)
            return true;//不执行父类点击事件
        return super.onKeyDown(keyCode, event);//继续执行父类其他点击事件
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }

}
